package com.xiaoniu.user.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoniu.common.base.service.BaseService;
import com.xiaoniu.cover.CoverUtils;
import com.xiaoniu.dto.UserQueryDto;
import com.xiaoniu.model.sys.SysUser;
import com.xiaoniu.user.listener.SysUserListener;
import com.xiaoniu.user.manager.UserManager;
import com.xiaoniu.user.mapper.SysUserMapper;
import com.xiaoniu.user.service.UserService;
import com.xiaoniu.vo.sys.SysUserExportVO;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangjianshan on 2021-05-01
 */
@Service
public class UserServiceImpl extends BaseService<SysUserMapper, SysUser> implements UserService {

    @Resource
    private UserManager userManager;

    /**
     * 分页查询用户列表
     *
     * @param pageNo       当前页
     * @param pageSize     每页多少条
     * @param userQueryDto 查询条件
     * @return
     */
    @Override
    public Page<SysUser> queryPageUserList(int pageNo, int pageSize, UserQueryDto userQueryDto) {
        Page<SysUser> pageUserList = userManager.queryPageUserList(pageNo, pageSize, userQueryDto);
        return pageUserList;
    }

    /**
     * 导出用户
     *
     * @param response
     */
    @Override
    @SneakyThrows
    public void download(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=user.xlsx");
        List<SysUser> userList = this.list();
        List<SysUserExportVO> voList = userList.stream().map(CoverUtils::cover).collect(Collectors.toList());
        EasyExcel.write(response.getOutputStream(), SysUserExportVO.class).sheet("user").doWrite(voList);
    }

    /**
     * 导入用户
     *
     * @param file
     */
    @Override
    @SneakyThrows
    public void importUser(MultipartFile file) {
        EasyExcel.read(file.getInputStream(), SysUserExportVO.class, new SysUserListener(userManager))
                .sheet()
                .doRead();
    }
}
